#-*- coding: utf-8 -*-

import requests
import json
import pandas as pd
import numpy as np
import warnings
import os

df_id = pd.read_excel('test_3000_postman.xlsx', dtype='str') # 读取3000条原始三要素
df_id = df_id.fillna('')
#df_id = df_id.sort_values(by='客户数据编号', ascending=True)
#del df_id['y变量']
df_id.head(5)


# {key:value for key, value in zip(features_var,['']*len(features_var))} # 入模变量变成字典格式

body_model = {
    "brData": {
        'alf_apirisk_time_lenth_all_sum': '',
        'alf_apirisk_time_slope_all_mean': '',
        'alf_apirisk_time_slope_all_sum': '',
        'alf_count_cell': '',
        'alf_ict_lenth_all_sum': '',
        'alf_ict_lenth_d180_sum': '',
        'alf_ict_lenth_d360_sum': '',
        'als_lst_cell_bank_inteday': '',
        'als_lst_id_bank_inteday': '',
        'als_m12_cell_bank_selfnum': '',
        'als_m12_cell_bank_tra_orgnum': '',
        'als_m12_cell_nbank_max_inteday': '',
        'als_m12_id_caon_allnum': '',
        'als_m1_id_bank_selfnum': '',
        'als_m3_cell_bank_selfnum': '',
        'als_m3_id_bank_selfnum': '',
        'als_m6_cell_bank_selfnum': '',
        'als_m6_id_min_inteday': '',
        'cf_cons_C29_amount': '',
        'cf_prob_cell': '',
        'cf_prob_max': '',
        'cf_prob_min': '',
        'ir_allmatch_days': '',
        'mma_var123': '',
        'mma_var149': '',
        'mma_var342': '',
        'mma_var345': '',
        'pd_cell_city_level': '',
        'pd_id_apply_age': '',
        'pd_id_city_new_house_sort': '',
        'pd_id_city_rent_sort': '',
        'pd_id_gender': '',
        'ql_m12_cell_bank_allnum': '',
        'ql_m12_id_bank_allnum': '',
        'ql_m12_id_bank_allnum_d': '',
        'ql_m12_id_bank_national_allnum': '',
        'ql_m12_id_max_monnum': '',
        'ql_m12_id_orgnum': '',
        'tl_id_t2_nbank_reamt': '',
        'tl_id_t4_nbank_reamt': '',
        'flag_ConsumptionFeature':'',
        'flag_multiplemodela':'',
        'flag_quantilelevel':'',
        'flag_inforelation':'',
        'flag_populationderivation':'',
        'flag_totalloan':'',
        'flag_ApplyFeature':'',
        'flag_applyloanstr':'',
    },
    "extraData": {
        "id": "522631199103218515",
        "cell": "18285598258",
        "user_date": "2021-07-14",
        "name": "吴荣远"
    },
    "outLevel": "1",
    "strategyType": None,
    "pointType": "scoresrevoloanjzd",
    "scoreData": "",
    "scoreBaseMealId": None,
    "swiftNumber": "",
    "scoreType": '[{"score":"scoresrevoloanjzd","api":"S1_0"}]',
    "apiCode": "4002474"
}

body = body_model.copy()
body_list = []
#读取3000条数据
df = pd.read_csv('test_3000_dts_result.csv',encoding='utf-8', dtype='str', sep=',',skiprows = [1])
df = df.fillna('')
df['cus_num'] = df['cus_num'].astype(int)
df.sort_values(by='cus_num', inplace=True)
df = df.reset_index(drop = True)

list_vars = list(body['brData'].keys())
list_extra = list(body['extraData'].keys())
list_vars.extend(list_extra)
list_vars.append('cus_num')
df = df[list_vars]
score = []
df_id = df_id.copy()
df_id['score'] = ''

for i in range(0, 3000):
    id_cell = df_id[df_id['客户数据编号'] == str(df.iloc[i]['cus_num'])]
    body = body_model.copy()
    for key1 in body_model['brData']:
        body['brData'][key1] = df.iloc[i][key1]
    for key2 in body_model['extraData']:
        if key2 == 'id':
            body['extraData'][key2] = id_cell.iloc[0]['身份证号']
        elif key2 == 'cell':
            body['extraData'][key2] = id_cell.iloc[0]['手机号']
        elif key2 == 'name':
            body['extraData'][key2] = id_cell.iloc[0]['姓名']
        else:
            body['extraData'][key2] = df.iloc[i][key2]

    body['inparam'] = body['extraData']
    body['brData'] = json.dumps(body['brData'])
    body['inparam'] = json.dumps(body['inparam'])
    body['extraData'] = json.dumps(body['extraData'])
    #print(i,body)
    re_ = requests.post('http://feature-k8s.100credit.cn/v1/get_model_result', json=body)
    re_ = re_.json()
    try:
        df_id.loc[df_id['客户数据编号']== str(df.iloc[i]['cus_num']), 'score'] = re_['resultData']['pointResult']['scoresrevoloanjzd']
        # df_id.loc[df_id['客户数据编号']== str(df.iloc[i]['cus_num']), 'var'] = re_['resultData']['scoreData']['scoreconsonxmlr']['derive']
    except:
        df_id.loc[df_id['客户数据编号'] == str(df.iloc[i]['cus_num']), 'score'] = ''
        # df_id.loc[df_id['客户数据编号'] == str(df.iloc[i]['cus_num']), 'var'] = ''

    # 衍生变量输出    
    # ft_data = json.loads(re_['resultData']['scoreData']['scoreconsonxmlr']['derive'])
    # for key,value in ft_data.items():
    #     df_id.loc[df_id['客户数据编号']== str(df.iloc[i]['cus_num']), key] = value
df_id.head(10)


body

re_

df_id['客户数据编号'] = df_id['客户数据编号'].astype('int')
df = df.drop(columns=[ 'id', 'cell', 'user_date', 'name'])
df.rename(columns = {'cus_num':'客户数据编号'},inplace=True)
df

result = pd.merge(df_id,df,how='left',on='客户数据编号')
result

result.to_excel('3000条线上提测结果.xlsx', index=False, encoding='utf-8')